<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Series extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'featured_image',
        'author_id',
        'post_count',
        'is_visible',
        'meta_title',
        'meta_description',
    ];

    protected $casts = [
        'is_visible' => 'boolean',
        'post_count' => 'integer',
    ];

    /**
     * 自定义路由模型绑定解析
     * 当路由使用 {series:slug} 时，通过slug查找系列
     */
    public function resolveRouteBinding($value, $field = null)
    {
        if ($field === 'slug') {
            return $this->where('slug', $value)->firstOrFail();
        }
        
        return $this->where($field ?? 'id', $value)->firstOrFail();
    }

    /**
     * 获取系列创建者
     */
    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    /**
     * 获取系列文章
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * 获取排序后的文章列表
     * 根据系列的 sort_mode 排序
     */
    public function getPostsOrdered()
    {
        $posts = $this->posts()->published();
        
        // 获取系列中第一篇文章的 sort_mode（系列内所有文章的 sort_mode 应该相同）
        $firstPost = $posts->first();
        $sortMode = $firstPost?->sort_mode ?? 'manual';
        
        if ($sortMode === 'published_at') {
            return $posts->orderBy('published_at', 'asc')->get();
        } else {
            return $posts->orderBy('series_order', 'asc')->get();
        }
    }

    /**
     * 查询可见的系列
     */
    public function scopeVisible($query)
    {
        return $query->where('is_visible', true);
    }

    /**
     * 自动生成 slug
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($series) {
            if (empty($series->slug)) {
                $series->slug = Str::slug($series->name);
            }
        });
    }
}
